/**
 * 自定义中间件
 */
import moment from "moment";
import koaLogger from "koa-logger";

// koa-logger
export const logger = function () {
    return koaLogger((str: string, args: any) => {
        console.log(`${moment().format('YYYY-MM-DD HH:mm:ss')}:${str}`);
    });
}
module.exports.logger = logger;

// api request
export const apiLog = async (ctx: any, next: any) => {
    console.log(`----------------------`);
    console.log("Request Data: ", ctx.request);
    await next();
    console.log("Response Data: ", ctx.response);
    console.log(`----------------------`);
}
module.exports.apiLog = apiLog;

// request time
export const timeLog = async (ctx: any, next: any) => {
    const start = new Date().getTime();
    await next();
    const ms = new Date().getTime() - start;
    console.log(`----------------------`);
    console.log(`USE TIME: ${ms}ms`);
    console.log(`----------------------`);
}
module.exports.timeLog = timeLog;

// apiResult
export const apiResult = async (ctx: any, next: any) => {
    await next();
    let code:number = 200;
    let msg: string = "";
    let data: any = ctx.body || '';

    return {
        code: code,
        msg: msg,
        data: data
    }
}

// api 404
export const apiNotFound = async (ctx: any, next: any) => {
    await next();
    if (ctx.status === 404) {
        ctx.body = {
            code: 404,
            msg: '404 Server Not Found!',
            data: ""
        };
    }
}
module.exports.apiNotFound = apiNotFound;

// api 401
export const noPermission = async (ctx: any, next: any) => {
    return next().catch((err: any) => {
        if(err.status === 401) {
            ctx.body = {
                code: 401,
                msg: '401 No Permission!',
                data: ""
            };
        }
    });
}
module.exports.noPermission = noPermission;